import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
    beforeEnter(to, from, next) {
      console.log("这是路由的独享守卫");
      next();
    },
  },
  {
    path: "/about",
    name: "about",

    component: () => import("../views/AboutView.vue"),
  },
  {
    path: "/login",
    name: "login",

    component: () => import("../views/login.vue"),
  },
];

const router = new VueRouter({
  // mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  console.log("这是全局前置守卫");
  // next();
  if (localStorage.getItem("token")) {
    next();
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next("/login");
    }
    //加一层判断防止死循环
  }
});

router.beforeResolve((to, from, next) => {
  console.log("这是全局的解析守卫");
  next();
});
//虽然beforeeach和beforeResolve都是在路由跳转之前执行 但是前者比后者之前的更加靠前 所以用beforeEach更多

router.afterEach((to, from) => {
  console.log("路由跳转完了");
});
//路由跳转完了 所以这里一般不写next

export default router;
